﻿
using MiddlewareCore.Middleware;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MiddlewareCore.Application
{
    /// <summary>
    /// 中间件应用入口
    /// </summary>
    public class ApplicationBuilder : IApplicationBuilder
    {
        private List<Func<RequestDelegate, RequestDelegate>> _middlewares = null;
        private RequestDelegate _end = null;
        public ApplicationBuilder()
        {
            _middlewares = new List<Func<RequestDelegate, RequestDelegate>>();
        }

        public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware)
        {
            if(null != middleware)
            {
                _middlewares.Add(middleware);
            }
            return this;
        }
        /// <summary>
        /// 将所有中间件添加到管道，待执行。
        /// </summary>
        private void Init()
        {
            _middlewares.Reverse();
            _end = (context) => { return Task.FromResult(0); };
            foreach(var middleware in _middlewares)
            {
                _end = middleware(_end);
            }
        }
        /// <summary>
        /// 中間件管道执行
        /// 执行此函数时，代表您已加入所有待执行中间件
        /// 所有中间件只初始化一次
        /// </summary>
        public async Task Work<T>(MiddlewareContext<T> context)
        {
            if (null == _end)
                Init();

            await _end.Invoke(context);
        }

        #region IDisposable
        public void Dispose()
        {
            try
            {
                _end = null;
                _middlewares.Clear();
            }
            catch { }
        }
        #endregion
    }
}
